import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/network/xindong_response.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/models/user/xindong_invite_user.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/common/xindong_invite_post_yemian.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/common/xindong_common_widget.dart';
import 'package:xindong/widgets/dialog/xindong_options_sheet.dart';
import 'package:xindong/widgets/xindong_avatar.dart';

class XinDongInviteClass {
  int fix_fencheng1 = 0;
  int fix_fencheng2 = 0;
  int fencheng_topup = 0;
  int subordinate_fencheng = 0;
  String yqm = "";

  XinDongInviteClass();

  factory XinDongInviteClass.fromJson(Map<String, dynamic> json) {
    return XinDongInviteClass()
      ..yqm = json['yqm']
      ..fix_fencheng1 = json['fix_fencheng1']
      ..fix_fencheng2 = json['fix_fencheng2']
      ..fencheng_topup = json['fencheng_topup']
      ..subordinate_fencheng = json['subordinate_fencheng'];
  }
}

class XinDongInviteLevelClass {
  int class_num = 0;
  String num = "0";
  String proportion = "0%";

  XinDongInviteLevelClass();

  factory XinDongInviteLevelClass.fromJson(Map<String, dynamic> json) {
    return XinDongInviteLevelClass()
      ..class_num = json['class_num']
      ..num = json['num']
      ..proportion = json['proportion'];
  }
}

class XinDongInviteYeMian extends StatefulWidget {
  const XinDongInviteYeMian({super.key});

  @override
  State<XinDongInviteYeMian> createState() => _XinDongInviteYeMianState();
}

class _XinDongInviteYeMianState extends State<XinDongInviteYeMian> {
  final RefreshController _refreshController = RefreshController(initialRefresh: true);
  int yemian = 0;
  bool hasMore = false; // 是否有下一页

  void _onRefresh() async {
    yemian = 1;
    final object = await XinDongNetworking.instance.request(XinDongApi.inviteTeam, parameters: {"page": yemian});
    if (object.code == XinDongServerStatus.success) {
      try {
        day_num = object.data["day_num"];
        total_num = object.data["total_num"];
        List list = object.data["list"];
        hasMore = list.isNotEmpty;
        inviteList = list.map((e) => XinDongInviteUser.fromJson(e)).toList();
      } catch (e) {
        mCatchPrint(e);
      }
      _refreshController.resetNoData();
      _refreshController.refreshCompleted();
    } else {
      _refreshController.refreshFailed();
    }
    setState(() {});
  }

  void _onLoading() async {
    if (!hasMore) {
      _refreshController.loadNoData();
      return;
    }
    yemian++;
    final object = await XinDongNetworking.instance.request(XinDongApi.inviteTeam, parameters: {"page": yemian});
    if (object.code == XinDongServerStatus.success) {
      try {
        List list = object.data["list"];
        hasMore = list.isNotEmpty;
        inviteList.addAll(list.map((e) => XinDongInviteUser.fromJson(e)).toList());
      } catch (e) {
        hasMore = false;
        mCatchPrint(e);
      }
      if (hasMore == false) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    } else {
      yemian--;
      _refreshController.loadFailed();
    }
    setState(() {});
  }

  XinDongInviteClass? inviteClass;
  List<XinDongInviteLevelClass> levelList = [];
  int day_num = 0;
  int total_num = 0;
  List<XinDongInviteUser> inviteList = [];

  @override
  void initState() {
    super.initState();

    Future.wait([
      XinDongNetworking.instance.request(XinDongApi.inviteLevelList),
      XinDongNetworking.instance.request(XinDongApi.inviteNum, parameters: {"yqm": ""}),
    ]).then((value) {
      List list = value;
      NetworkResponse levelObject = list.first;
      NetworkResponse inviteNumObject = list.last;

      if (inviteNumObject.code == XinDongServerStatus.success) {
        inviteClass = XinDongInviteClass.fromJson(inviteNumObject.data);
      }
      if (levelObject.code == XinDongServerStatus.success) {
        List list = levelObject.data;
        levelList = list.map((e) => XinDongInviteLevelClass.fromJson(e)).toList();
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XinDongAppBar("邀请好友"),
      body: ListView(
        children: [
          Stack(
            children: [
              ImageUtil.asset(AssetsRes.IMAGE_INVITE_TOP),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(-0.4, -0.15),
                  child: Text(
                    "${inviteClass?.fix_fencheng1 ?? 0}%",
                    style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 38),
                  ),
                ),
              ),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(0.4, -0.15),
                  child: Text(
                    "${inviteClass?.fix_fencheng2 ?? 0}%",
                    style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 38),
                  ),
                ),
              ),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(0.0, 0.58),
                  child: GestureDetector(
                    onTap: () {
                      XinDongOptionsSheet.show(
                        dataList: const ["海报", "链接"],
                        onSelect: (index) {
                          if (index == 0) {
                            XinDongPageSingleton.instance
                                .pushYeMian(XinDongInvitePostYeMian(url: XinDongNetworking.instance.downloadUrl));
                          } else if (index == 1) {
                            Clipboard.setData(ClipboardData(text: XinDongNetworking.instance.downloadUrl));
                            showToast("复制成功");
                          } else if (index == 1) {}
                        },
                      );
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      width: 200,
                      height: 50,
                      color: Colors.transparent,
                    ),
                  ),
                ),
              ),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(0.0, 0.9),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        inviteClass?.yqm ?? "",
                        style: const TextStyle(color: Colors.blueAccent, fontSize: 30),
                      ),
                      const SizedBox(width: 20),
                      GestureDetector(
                        onTap: () {
                          Clipboard.setData(ClipboardData(text: "${inviteClass?.yqm}"));
                          showToast("复制成功");
                        },
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          height: 30,
                          padding: const EdgeInsets.only(left: 16, right: 16),
                          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(26)),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                "复制",
                                style: TextStyle(fontSize: 18, color: DZColors.hexStringColor("#F345AE"), height: 1.2),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          Stack(
            children: [
              SizedBox(
                width: screenWidth,
                height: screenWidth * 1354 / 750,
                child: ImageUtil.asset(AssetsRes.IMAGE_INVITE_CENTER),
              ),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(-0.6, -0.78),
                  child: Text(
                    "${inviteClass?.fencheng_topup ?? 0}%",
                    style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 38),
                  ),
                ),
              ),
              Positioned.fill(
                child: Align(
                  alignment: const Alignment(0.6, -0.78),
                  child: Text(
                    "${inviteClass?.subordinate_fencheng ?? 0}%",
                    style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 38),
                  ),
                ),
              ),
              Positioned.fill(
                left: 30,
                right: 30,
                child: Align(
                  alignment: const Alignment(-1.0, -0.3),
                  child: levelView(),
                ),
              ),
              Positioned.fill(
                left: 30,
                right: 30,
                child: Align(
                  alignment: const Alignment(-1.0, 0.5),
                  child: Html(data: """ <p style="font-weight: bold;margin-top: 5%;margin-bottom: 2%;">奖励说明</p>
    <p style="font-size: 15px;">* 好友充值固定获得20%的奖励，好友充值100元，你得20元。</p>
    <p style="font-size: 15px;">*根据累计邀请认证嘉宾的女性人数不同收益比例有所不同，好友未认证成为女性嘉宾的,无法从好友身上获取奖励，也不计算邀请认证人数。</p>
    """),
                ),
              ),
            ],
          ),
          Stack(children: [
            ImageUtil.asset(AssetsRes.IMAGE_INVITE_BOTTOM),
            Positioned.fill(
              child: Align(
                alignment: const Alignment(-0.45, -0.675),
                child: Text(
                  "$day_num",
                  style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 20),
                ),
              ),
            ),
            Positioned.fill(
              child: Align(
                alignment: const Alignment(0.85, -0.675),
                child: Text(
                  "$total_num",
                  textAlign: TextAlign.left,
                  style: TextStyle(color: DZColors.hexStringColor("#F345AE"), fontSize: 20),
                ),
              ),
            ),
            Positioned.fill(
              left: 30,
              right: 30,
              top: 100,
              bottom: 30,
              child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                controller: _refreshController,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child: ListView.separated(
                  itemCount: inviteList.length,
                  itemBuilder: (BuildContext context, int index) {
                    final model = inviteList[index];
                    return SizedBox(
                      height: 60,
                      child: Row(
                        children: [
                          XinDongAvatar(url: model.getAvatar, size: 46),
                          const SizedBox(width: 10),
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    Clipboard.setData(ClipboardData(text: model.uid));
                                    showToast("已复制ID");
                                  },
                                  behavior: HitTestBehavior.opaque,
                                  child: Row(
                                    children: [
                                      Text(
                                        "id：${model.uid}",
                                        style: const TextStyle(fontSize: 15, color: DZColors.titleColor),
                                      ),
                                      Container(
                                        height: 18,
                                        padding: const EdgeInsets.only(left: 8, right: 8),
                                        margin: const EdgeInsets.only(left: 8, right: 8),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(18),
                                          border: Border.all(color: DZColors.contentColor, width: 1.0),
                                        ),
                                        child: const Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Text(
                                              "复制",
                                              style: TextStyle(fontSize: 14, color: DZColors.contentColor, height: 1.2),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                const SizedBox(height: 3),
                                Text(
                                  "昵称：${model.name}",
                                  style: const TextStyle(fontSize: 13, color: DZColors.titleColor),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            width: 75,
                            child: Text(
                              "${model.register_datetime}",
                              textAlign: TextAlign.center,
                              style: const TextStyle(fontSize: 14, color: DZColors.contentColor),
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return commonDivider(indent: 0, endIndent: 0);
                  },
                ),
              ),
            ),
          ]),
        ],
      ),
    );
  }

  Widget levelView() {
    const titleTextStyle = TextStyle(color: DZColors.titleColor, fontSize: 15);
    const rowTextStyle = TextStyle(color: DZColors.placeholderColor, fontSize: 15);
    return Container(
      width: double.infinity,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.orange, width: 1.0),
      ),
      child: Table(
        border: const TableBorder(
          horizontalInside: BorderSide(color: Colors.orange, width: 0.5),
          verticalInside: BorderSide(color: Colors.orange, width: 0.5),
        ),
        columnWidths: const {
          0: FixedColumnWidth(1),
          1: FixedColumnWidth(3),
          2: FixedColumnWidth(3),
        },
        children: [
          // 标题
          TableRow(children: [
            Container(height: 32, alignment: Alignment.center, child: const Text("等级", style: titleTextStyle)),
            Container(height: 32, alignment: Alignment.center, child: const Text("邀请人数", style: titleTextStyle)),
            Container(height: 32, alignment: Alignment.center, child: const Text("收益奖励", style: titleTextStyle)),
          ]),
          // 列表
          for (XinDongInviteLevelClass model in levelList)
            TableRow(children: [
              Container(
                height: 32,
                alignment: Alignment.center,
                child: Text("${model.class_num}", style: rowTextStyle),
              ),
              Container(
                height: 32,
                alignment: Alignment.center,
                child: Text(model.num, style: rowTextStyle),
              ),
              Container(
                height: 32,
                alignment: Alignment.center,
                child: Text(model.proportion, style: rowTextStyle),
              ),
            ]),
        ],
      ),
    );
  }
}
